const uuid = require('uuid');
const oss = require('../module/tool/oss');
const sysConfig = require('../../config/sys.json');
const ossConfig = require('../../config/oss.json');
const fs = require('fs');

async function commonUpload (file) {
    let filePath = file.path;
    let backName = filePath.slice(filePath.lastIndexOf('.'));
    let frontName = uuid.v1().toString().replace(/-/g, '');
    if (sysConfig.isEnableOss) {
        const directory = `/${ossConfig.baseDirectory}/`;
        let fileName = directory + frontName + backName;
        // 上传文件
        await oss.uploadFile(fileName, file.path);
        return oss.getCdnUrl() + fileName;
    } else {
        const fileName = frontName + backName;
        const destPath = sysConfig.publicPath + '/' + fileName;
        const readStream = fs.createReadStream(filePath);
        const writeStream = fs.createWriteStream(destPath);
        readStream.pipe(writeStream);
        return sysConfig.localFileViewHost + '/' + fileName;
    }
}

module.exports = {
    commonUpload
};
